<script setup>
import { ref ,getCurrentInstance, reactive, onMounted, nextTick} from 'vue'
import {ElMessage,ElMessageBox} from "element-plus"
const handleClick = () => {
  console.log('click')
}

const tableData = ref([])

const {proxy} = getCurrentInstance()
const getUserData = async ()=> {
    let data = await proxy.$api.getUserData(config)
    tableData.value = data.list.map(item => ({
        // return {
            ...item,
            // sexLabel : item.sex === '1' ? '男' : '女'
            //下面是ai解决的，另一个在184行，这样性别编辑就没问题了
            sexLabel: (item.sex === 1 || item.sex === '1') ? '男' : '女'
        // }
    }))
    config.total = data.count
}
//deepseek写的
// const getUserData = async () => {
//   try {
//     let data = await proxy.$api.getUserData();
//     console.log(data);
//     tableData.value = data.list.map(item => ({
//       ...item,
//       sexLabel: item.sex === 1 ? '男' : '女'
//     }));
//   } catch (error) {
//     console.error('获取用户数据失败:', error);
//   }
// }

const tableLabel = reactive([
    {
        prop:'name',
        label:'姓名'
    },
    {
        prop:'age',
        label:'年龄'
    },
    {
        prop:'sexLabel',
        label:'性别'
    },
    {
        prop:'birth',
        label:'出生日期',
        width:200
    },
    {
        prop:'addr',
        label:'家庭地址',
        width:200
    },
])
//61-70是搜索功能
const formInline = reactive({
    name:''
})
const config = reactive({
    name:'',
    total:0,
    page:1
})

//搜索功能
const handleSearch = ()=>{
    config.name = formInline.keyWord,
    getUserData()
}

//换页功能
const handleChange = (page)=> {
    config.page = page
    getUserData()
}

//删除功能
const handleDelete = (value)=>{
    ElMessageBox.confirm("您确定要删除吗？").then(async ()=>{
        await proxy.$api.deleteUser({id:value.id})
        ElMessage({
            showClose: true,
            message: "删除成功",
            type: "success",
        })
        getUserData()
    })
    
}

//下面是新增功能（前三个是默认的值）
const action = ref('add')
const dialogVisible =ref(false)
const formUser = reactive({
    sex:'1'//性别默认是男
})

//表单校验规则(直接拿过来的)
const rules = reactive({
  name: [{ required: true, message: "姓名是必填项", trigger: "blur" }],
  age: [
    { required: true, message: "年龄是必填项", trigger: "blur" },
    { type: "number", message: "年龄必须是数字" },
  ],
  sex: [{ required: true, message: "性别是必选项", trigger: "change" }],
  birth: [{ required: true, message: "出生日期是必选项" }],
  addr:[{ required: true, message: '地址是必填项' }]
})

//关闭模态框
const handleClose = ()=>{
    dialogVisible.value = false
    proxy.$refs['userForm'].resetFields()//重置模态框
}
//取消模态框
const handleCancel = ()=> {
    dialogVisible.value = false
    proxy.$refs['userForm'].resetFields()//重置模态框
}
//增加按钮
const handleAdd = ()=> {
    dialogVisible.value = true
    action.value = 'add'
}

//下面是对birth数据的处理
const timeFormat = ()=> {
    var time = new Date(time)
    var year = time.getFullYear()
    var month = time.getMonth() + 1
    var data = time.getDate()
    function add(m){
        return m < 10 ? "0"+m : m
    }
    return year + "-" + add(month) + "-" + add(data)
}
const onSubmit = ()=> {
    //先要校验
    proxy.$refs['userForm'].validate(async (vaild)=> {
        if(vaild){
            let res = null
            formUser.birth = /^\d{4}-\d{2}-\d{2}$/.test(formUser.birth) ? formUser.birth : timeFormat(formUser.birth)
            if(action.value === 'add'){
                res = await proxy.$api.addUser(formUser)
            }else{
                res = await proxy.$api.editUser(formUser)
            }
            //下面的是有了res以后的
            if(res){
                dialogVisible.value = false
                proxy.$refs['userForm'].resetFields()
                getUserData()
                //148-161是自己添加的代码
                if(action.value === 'add'){
                    ElMessage({
                    showClose: true,
                    message: "添加成功",
                    type: "success",
                })
                }else{
                    ElMessage({
                    showClose: true,
                    message: "编辑成功",
                    type: "success",
                })
                }
                
            }else{
                ElMessage({
                    showClose:true,
                    message:'请输入正确的内容',
                    type:'error'
                })
            }
        }
    })

}

//编辑功能（下面那个问题是实际开发也会碰到的问题）
const handleEdit = (value)=> {
    action.value = 'edit'
    dialogVisible.value = true
    //下面进行一个延迟加载以及浅拷贝，因为浅拷贝加载太快，上面一行代码还没执行完浅拷贝就执行完了，所以这时候模态框会把浅拷贝的值当作模态框的初始值
    nextTick(()=> {
        // Object.assign(formUser,{...value,sex:''+value.sex})，assign是一个浅拷贝方法
        Object.assign(formUser,{...value,sex:value.sex === 1  ? '男' : '女'})
    })

}


onMounted(() => {
    getUserData()
})

</script>

<template>
    <div class="user-header">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-form :inline="true" :model="formInline">
            <!-- :model="formInline"：指定绑定的数据模型，formInline 是 Vue 实例中的一个数据对象，它会保存表单的输入内容。所有表单项的值都会与这个模型同步。 -->
            <!-- :inline="true" 是一个 Vue.js 的动态绑定语法，意思是将 inline 属性的值设置为 true，使得表单元素呈现行内布局（即在同一行展示表单项，而不是每个表单项占据一行）。如果这个值为 false 或不设置，表单项会以块级元素的方式显示，通常是每个表单项占据一行。 -->
            <el-form-item label="请输入">
                <el-input placeholder="请输入用户名" v-model="formInline.keyWord"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
            </el-form-item>
        </el-form>
    </div>
    <div class="table">
        <el-table :data="tableData" style="width: 100%">
            <el-table-column 
            v-for="item in tableLabel"
            :key="item.label"
            :width="item.width ? item.width : 125"
            :prop="item.prop"
            :label="item.label"/>
            <el-table-column fixed="right" label="Operations" min-width="120">
            <template #="scope"><!-- 通过插槽把数据传给删除按钮 -->
                <el-button  type="primary" size="small" @click="handleEdit(scope.row)">
                编辑
                </el-button>
                <el-button  type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
            </el-table-column>
        </el-table>
        <el-pagination 
        background 
        layout="prev, pager, next" 
        :total="config.total" 
        @current-change="handleChange"
        class="pager"
         />
    </div>
    <el-dialog
        v-model="dialogVisible"
        :title="action == 'add' ? '新增用户' : '编辑用户'"
         width="35%"
        :before-close="handleClose"
        >
        <!--需要注意的是设置了:inline="true"，
            会对el-select的样式造成影响，我们通过给他设置一个class=select-clearn
            在css进行处理-->
        <el-form :inline="true"  :model="formUser" :rules="rules" ref="userForm">
        <el-row>
            <el-col :span="12">
            <el-form-item label="姓名" prop="name">
                <el-input v-model="formUser.name" placeholder="请输入姓名" />
            </el-form-item>
            </el-col>
            <el-col :span="12">
            <el-form-item label="年龄" prop="age">
                <el-input v-model.number="formUser.age" placeholder="请输入年龄" />
            </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="12">
            <el-form-item class="select-clearn" label="性别" prop="sex">
                <el-select  v-model="formUser.sex" placeholder="请选择">
                <el-option label="男" value="1" />
                <el-option label="女" value="0" />
                </el-select>
            </el-form-item>
            </el-col>
            <el-col :span="12">
            <el-form-item label="出生日期" prop="birth">
                <el-date-picker
                v-model="formUser.birth"
                type="date"
                placeholder="请输入"
                style="width: 100%"
                />
            </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-form-item
            label="地址"
            prop="addr"
            >
            <el-input v-model="formUser.addr" placeholder="请输入地址" />
            </el-form-item>
        </el-row>
        <el-row style="justify-content: flex-end">
            <el-form-item>
            <el-button type="primary" @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="onSubmit">确定</el-button>
            </el-form-item>
        </el-row>
        </el-form>
    </el-dialog>
</template>

<style lang="less" scoped>
.user-header{
    display: flex;
    justify-content: space-between;
}
.table{
   position:relative;
   height:535px;
   .pager{
      position:absolute;
      right:10px;
      bottom: 0px;
   }
   .el-table{
      width:100%;
      height:500px;
   }
}
.select-clearn{
    display: flex;
}
</style>